<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Complete openID login
 * 
 * Completes the processing of an openID login.
 * Adds errors to $this->requestAttributes['errorMessages'].
 * On failure, jumps to the action identified by $_REQUEST['onFailure'].
 * On success, jumps to the action identified by $_REQUEST['onSuccess'].
 * Adds openid_identifier and if available: openid_email, openid_firstname and openid_lastname to $_SESSION
 */
class escape_repositoryui_action_CompleteOpenIdLogin extends escape_repositoryui_Action
{
	public function handleRequest()
	{
		// PHP4 code in the php-openid library causes a lot of warnings
		error_reporting(E_ALL ^ E_COMPILE_WARNING ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
		require_once("php-openid-2/include.php");
	
		session_start();
	
		/* @var $repository escape_repository_Repository */
		$repository =& $this->requestAttributes['repository'];

		// get the error messages queue
		$errorMessages =& $this->requestAttributes['errorMessages'];
		if(!isset($errorMessages))
		{
			$errorMessages = array();
		}

		$onSuccess = $_GET['onSuccess'];
		if(!isset($onSuccess))
		{
			print "Invalid request";
			return null;
		}
		$onFailure = $_GET['onFailure'];
		if(!isset($onFailure))
		{
			print "Invalid request";
			return null;
		}
		
		// build a return to URL (for verification)
		$requestParamters = array_merge($_GET, $_POST);
		unset($requestParamters['action']);
		unset($requestParamters['openid']);
		$returnTo = $repository->config['server_url'] . '/completeOpenIdLogin?' . http_build_query($requestParamters);
		
		// get the openID file store
		$openIdStorePath = $repository->config['openid_store_path'] . $repository->config['virtualhost'] . '/';
		$store = new Auth_OpenID_FileStore($openIdStorePath);
		
		// get the openID consumer
		$consumer = new Auth_OpenID_Consumer($store);
		
		// process OpenID login result
		
		// remove 'action' from the query string to prevent the return_to check from failing
		// the 'action' parameter was added to the URL by a rewrite operation
		$queryStringArray = explode('&', $_SERVER['QUERY_STRING']);
		$filteredQueryStringArray = array();
		foreach($queryStringArray as $value)
		{
			if(!preg_match('/^action=/', $value))
			{
				$filteredQueryStringArray[] = $value;
			}
		}
		$_SERVER['QUERY_STRING'] = implode('&', $filteredQueryStringArray);

		$response = $consumer->complete($returnTo);

		// Check the response status.
		if($response->status == Auth_OpenID_CANCEL)
		{
			// This means the authentication was cancelled.
			$errorMessages[] = 'Verification cancelled.';
		}
		else if($response->status == Auth_OpenID_FAILURE)
		{
			// Authentication failed; display the error message.
			$errorMessages[] = "OpenID authentication failed: " . $response->message;
		}
		else if ($response->status == Auth_OpenID_SUCCESS)
		{
			// Authentication succeeded
			
			// Extract the identity URL
			$identityUrl = $response->identity_url;
			if(!$identityUrl)
			{
				$identityUrl = $response->getDisplayIdentifier();
			}

			if(!$identityUrl)
			{
				$errorMessages[] = 'OpenID authentication failed: ' . $response->message;
			}
			else
			{
				$_SESSION['openid_identifier'] = $identityUrl;
				
//				// extract the Simple Registration data (if it was returned)
//				$sregResponse = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
//	
//				$sreg = $sregResponse->contents();
//	
//				if (@$sreg['email'])
//				{
//					$success .= "  You also returned '".htmlspecialchars($sreg['email'])."' as your email.";
//				}
//	
//				if (@$sreg['nickname'])
//				{
//					$success .= "  Your nickname is '".htmlspecialchars($sreg['nickname'])."'.";
//				}
//	
//				if (@$sreg['fullname'])
//				{
//					$success .= "  Your fullname is '".htmlspecialchars($sreg['fullname'])."'.";
//				}
//				
//				escape_printr_pre($success);
	
				// extract attribute exchange data, if available
				$ax = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
				if($ax)
				{
					$_SESSION['openid_email'] = $ax->getSingle('http://schema.openid.net/contact/email', null);
					$_SESSION['openid_firstname'] = $ax->getSingle('http://schema.openid.net/namePerson/first', null);
					if($_SESSION['openid_firstname'] === null)
					{
						$_SESSION['openid_firstname'] = $ax->getSingle('http://axschema.org/namePerson/first', null);
					}
					$_SESSION['openid_lastname'] = $ax->getSingle('http://schema.openid.net/namePerson/last', null);
					if($_SESSION['openid_lastname'] === null)
					{
						$_SESSION['openid_lastname'] = $ax->getSingle('http://axschema.org/namePerson/last', null);
					}
				}
				
				return 'action::' . $onSuccess;
			}
		}
		
		$this->requestAttributes['errorMessages'] =& $errorMessages;
		
		return 'action::' . $onFailure;
	}
}